package com.feiyisys.utils;

import com.feiyisys.config.TenxunVideoConfig;
import com.qcloud.vod.VodUploadClient;
import com.qcloud.vod.exception.VodClientException;
import com.qcloud.vod.model.VodUploadRequest;
import com.qcloud.vod.model.VodUploadResponse;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 腾讯云视频点播上传工具类（支持分片上传）
 */
@Slf4j
@Component
public class TencentVodUtil {

    @Resource
    private TenxunVideoConfig videoConfig;

    // 分片大小阈值（5MB），超过这个大小会自动启用分片上传
    private static final long CHUNK_SIZE_THRESHOLD = 5 * 1024 * 1024L;

    /**
     * 初始化VOD上传客户端
     */
    private VodUploadClient initVodClient() {
        return new VodUploadClient(videoConfig.getSecretId(), videoConfig.getSecretKey());
    }

    /**
     * 上传视频文件（自动分片）
     */
    public VodUploadResponse uploadVideo(MultipartFile mediaFile) {
        return uploadVideo(mediaFile, null, null, null);
    }

    /**
     * 上传视频文件（带封面，自动分片）
     */
    public VodUploadResponse uploadVideo(MultipartFile mediaFile, MultipartFile coverFile) {
        return uploadVideo(mediaFile, coverFile, null, null);
    }

    /**
     * 高级上传方法（支持自定义分片参数）
     * @param mediaFile 视频文件
     * @param coverFile 封面文件
     * @param chunkSize 自定义分片大小（字节），null则使用SDK默认值
     * @param concurrentUploadNumber 并发上传数，null则使用SDK默认值
     * @return 上传响应
     */
    public VodUploadResponse uploadVideo(MultipartFile mediaFile, MultipartFile coverFile,
                                         Long chunkSize, Integer concurrentUploadNumber) {
        VodUploadClient vodClient = null;
        File tempMediaFile = null;
        File tempCoverFile = null;

        try {
            // 验证视频文件
            validateMediaFile(mediaFile);

            // 创建临时文件
            tempMediaFile = createTempFile(mediaFile, "video");
            if (coverFile != null && !coverFile.isEmpty()) {
                tempCoverFile = createTempFile(coverFile, "cover");
            }

            // 检查文件大小并决定是否启用分片上传
            long fileSize = mediaFile.getSize();
            boolean shouldUseChunkUpload = shouldUseChunkUpload(fileSize);

            log.info("文件大小: {} MB, 启用分片上传: {}", fileSize / 1024 / 1024, shouldUseChunkUpload);

            // 初始化VOD客户端
            vodClient = initVodClient();

            // 创建上传请求并配置分片参数
            VodUploadRequest request = buildUploadRequest(tempMediaFile, tempCoverFile,
                    chunkSize, concurrentUploadNumber);

            // 执行上传（SDK会自动处理分片逻辑）
            VodUploadResponse response = vodClient.upload(videoConfig.getRegion(), request);

            logUploadResult(response, fileSize, shouldUseChunkUpload);
            return response;

        } catch (VodClientException e) {
            log.error("腾讯云VOD客户端异常: {}", e.getMessage());
            throw new RuntimeException("视频上传失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("视频上传异常: {}", e.getMessage());
            throw new RuntimeException("视频上传失败: " + e.getMessage());
        } finally {
            cleanupTempFiles(tempMediaFile, tempCoverFile);
        }
    }

    /**
     * 验证媒体文件
     */
    private void validateMediaFile(MultipartFile mediaFile) {
        if (mediaFile == null || mediaFile.isEmpty()) {
            throw new RuntimeException("视频文件不能为空");
        }

        String originalFilename = mediaFile.getOriginalFilename();
        if (originalFilename == null || !originalFilename.contains(".")) {
            throw new RuntimeException("视频文件格式不正确");
        }

        // 可以添加文件类型验证
        String extension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
        if (!isSupportedVideoFormat(extension)) {
            throw new RuntimeException("不支持的视频格式: " + extension);
        }
    }

    /**
     * 判断是否应该使用分片上传
     */
    private boolean shouldUseChunkUpload(long fileSize) {
        return fileSize > CHUNK_SIZE_THRESHOLD;
    }

    /**
     * 构建上传请求
     */
    private VodUploadRequest buildUploadRequest(File mediaFile, File coverFile,
                                                Long chunkSize, Integer concurrentUploadNumber) {
        VodUploadRequest request = new VodUploadRequest();
        request.setMediaFilePath(mediaFile.getAbsolutePath());

        // 设置分类ID
        Long classId = 1500042562L;
        request.setSubAppId(classId);

        // 设置封面文件
        if (coverFile != null) {
            request.setCoverFilePath(coverFile.getAbsolutePath());
        }

        // 配置分片参数（如果提供）
        if (chunkSize != null) {
            // 设置分片大小（字节），腾讯云VOD SDK可能会提供相应的方法
            // request.setChunkSize(chunkSize);
        }

        if (concurrentUploadNumber != null) {
            // 设置并发上传数，腾讯云VOD SDK可能会提供相应的方法
             request.setConcurrentUploadNumber(concurrentUploadNumber);
        }

        return request;
    }

    /**
     * 记录上传结果
     */
    private void logUploadResult(VodUploadResponse response, long fileSize, boolean usedChunkUpload) {
        String fileId = response.getFileId();
        log.info("视频上传成功 - FileId: {}, 文件大小: {} MB, 分片上传: {}, MediaUrl: {}",
                fileId, fileSize / 1024 / 1024, usedChunkUpload, response.getMediaUrl());
    }

    /**
     * 支持的视频格式
     */
    private boolean isSupportedVideoFormat(String extension) {
        String[] supportedFormats = {"mp4", "avi", "mov", "wmv", "flv", "mkv", "m4v", "3gp"};
        for (String format : supportedFormats) {
            if (format.equals(extension)) {
                return true;
            }
        }
        return false;
    }

    // 以下方法保持不变...
    private File createTempFile(MultipartFile file, String type) {
        try {
            String originalFilename = file.getOriginalFilename();
            String suffix = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            }

            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String tempFileName = String.format("%s_%s%s", type, uuid, suffix);

            File tempFile = new File(System.getProperty("java.io.tmpdir"), tempFileName);
            file.transferTo(tempFile);

            log.debug("创建临时文件: {}", tempFile.getAbsolutePath());
            return tempFile;

        } catch (IOException e) {
            log.error("创建临时文件失败: {}", e.getMessage());
            throw new RuntimeException("文件处理失败: " + e.getMessage());
        }
    }

    private void cleanupTempFiles(File... files) {
        for (File file : files) {
            if (file != null && file.exists()) {
                try {
                    boolean deleted = file.delete();
                    if (deleted) {
                        log.debug("删除临时文件成功: {}", file.getAbsolutePath());
                    } else {
                        log.warn("删除临时文件失败: {}", file.getAbsolutePath());
                    }
                } catch (Exception e) {
                    log.warn("删除临时文件异常: {}", e.getMessage());
                }
            }
        }
    }

    public String getVideoUrl(String fileId) {
        if (fileId == null || fileId.isEmpty()) {
            return "";
        }

        if (fileId.startsWith("http://") || fileId.startsWith("https://")) {
            return fileId;
        }

        String baseUrl = videoConfig.getBaseurl();
        if (baseUrl != null && !baseUrl.isEmpty()) {
            if (baseUrl.endsWith("/")) {
                return baseUrl + fileId;
            } else {
                return baseUrl + "/" + fileId;
            }
        }

        return fileId;
    }
}